package com.hyt.it.ogt.ks.websocket;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.hyt.it.ogt.ks.service.IApplyCheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;


/**
 * 监听考试考试期间是否在线和离线
 *
 * @author 刘恒活
 * @since 2020/7/14 9:11
 */
@ServerEndpoint("/ks/ws/candidate/{examId}/{candidateId}")
@Component
@Slf4j
public class CandidateExamOnlineListener {

    private static CandidateWebSocketService candidateWebSocketService;

    private static IApplyCheckService applyCheckService;

    @Autowired
    public void setCandidateWebSocketService(CandidateWebSocketService candidateWebSocketService) {
        CandidateExamOnlineListener.candidateWebSocketService = candidateWebSocketService;
    }

    @Autowired
    public void setCandidateLogOtherService(IApplyCheckService applyCheckService) {
        CandidateExamOnlineListener.applyCheckService = applyCheckService;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("examId") String examId, @PathParam("candidateId") String candidateId) {
        log.info("有考生【{}】，【{}】，【{}】加入连接", examId, candidateId, session.getId());
        candidateWebSocketService.addSession(session, examId, candidateId);

        // 检测考生是否有为确认的审核过的人脸核身异常、设备检测异常 有的话给主动推送消息
        try {
            applyCheckService.wsOpenCheckAndSendApplyResult(examId, candidateId);
        } catch (Exception e) {
            log.error("考生连接上之后给考生发送消息报错：", e);
        }
    }

    /**
     * 连接关闭调用的方法
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        log.info("=====websocket断开====onClose==============", session.getId());
        candidateWebSocketService.removeSession(session);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到客户端发送的消息：【{}】，【{}】", message, session.getId());
        candidateWebSocketService.onMessage(message, session);
    }

    /**
     * 出现错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("监听考生是否在线，发生错误：{}，Session ID： {}", error, session.getId());
        candidateWebSocketService.onError(session, error);
    }

}
